package com.storm.axactivity;

import android.os.Bundle;
import android.widget.EditText;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.storm.axactivity.controller.DeviceController;
import com.storm.axactivity.sqlite.Device;

public class ModifyActivity extends SherlockActivity {

	int Position = -1;
	EditText etName;
	EditText etIp;
	EditText etPort;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_modify);

		Bundle bundle = this.getIntent().getExtras();
		Position = bundle.getInt("Position");
		// String s1=bundle.getString("key1");
		// Toast.makeText(this, Integer.toString(Position), Toast.LENGTH_SHORT)
		// .show();

		getSupportActionBar().setDisplayHomeAsUpEnabled(true);

		if (-1 != Position) {
			Device dev = DeviceController.getInstance().getItem(Position);

			etName = (EditText) findViewById(R.id.modify_ax_name_value);
			etIp = (EditText) findViewById(R.id.modify_ax_ip_value);
			etPort = (EditText) findViewById(R.id.modify_ax_port_value);

			etName.setText(dev.name);
			etIp.setText(dev.ip);
			etPort.setText(Integer.toString(dev.port));
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub

		menu.add(0, R.id.modify_ax_menu_ok, 0,
				R.string.add_modify_ax_menu_ok)
		// .setIcon(isLight ? R.drawable.ic_compose_inverse :
		// R.drawable.ic_compose)
				.setShowAsAction(
						MenuItem.SHOW_AS_ACTION_IF_ROOM
								| MenuItem.SHOW_AS_ACTION_WITH_TEXT);

		menu.add(0, R.id.modify_ax_menu_cancel, 0,
				R.string.add_modify_ax_menu_cancel)
		// .setIcon(isLight ? R.drawable.ic_refresh_inverse :
		// R.drawable.ic_refresh)
				.setShowAsAction(
						MenuItem.SHOW_AS_ACTION_IF_ROOM
								| MenuItem.SHOW_AS_ACTION_WITH_TEXT);

		return true;

		// return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			return true;
		case R.id.modify_ax_menu_ok:
			// etName.setText(dev.name);
			// etIp.setText(dev.ip);
			// etPort.setText(Integer.toString(dev.port));
			if (-1 != Position) {
				Device Device = new Device();  
				Device.name = etName.getText().toString();
				Device.ip = etIp.getText().toString();
				Device.port = Integer.parseInt(etPort.getText().toString());
				
				DeviceController.getInstance().modifyItem(Position, Device);
			}

			finish();
			return true;
		case R.id.modify_ax_menu_cancel:
			finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}

		// return super.onOptionsItemSelected(item);
	}
}
